package com.ufo.store.management.ui.activity;

import com.nineoldandroids.view.ViewHelper;
import com.ufo.store.management.R;
import com.ufo.store.management.ui.fragment.AccountFragment;
import com.ufo.store.management.ui.fragment.HomeFragment;
import com.ufo.store.management.ui.fragment.MonitorFragment;
import com.ufo.store.management.common.Config;
import com.ufo.store.management.utils.DialogUtil;
import com.ufo.store.management.utils.Utils;
import com.ufo.store.management.widget.viewpager.NoScrollViewPager;
import com.ufo.store.management.widget.dialog.InputDialog;

import android.Manifest;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.util.List;


public class MainActivity extends BaseActivity {
	private long exitTime = 0;

	private NoScrollViewPager mContentViewPager;
	private HomeFragment mHomeFragment;
	private MonitorFragment mMonitorFragment;
	private AccountFragment mAccountFragment;

	private DrawerLayout mDrawerLayout;

	private InputDialog mInputDialog;

	private int viewpageSize = 3;
	private BottomNavigationView bottomNavigationView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initData();
		initView();
		//软件注册/正版授权
//		new android.os.Handler().postDelayed(new Runnable() {
//			@Override
//			public void run() {
//				autoMaticCheckCopyright();
//			}
//		}, 500);

		this.setListener(new PermissionListener() {
			// 申请到所需全部权限
			@Override
			public void onGranted(int permissionRequestCode) {
				if (mPermissionRequestCode == permissionRequestCode){
					//Toast.makeText(MainActivity.this,"已获取到相关权限！进行后续操作！",Toast.LENGTH_SHORT).show();
				}
			}

			// 未申请到所需全部权限
			@Override
			public void onDenied(List<String> deniedPermission, int permissionRequestCode) {
				if (mPermissionRequestCode == permissionRequestCode){
					//Toast.makeText(MainActivity.this,"未获取到相关权限！不能进行后续操作！",Toast.LENGTH_SHORT).show();
				}
			}
			// 未申请到所需全部权限，并存在部分权限勾选了不再提示选项。
			@Override
			public void onShouldShowRationale(List<String> deniedPermission, int permissionRequestCode) {
				if (mPermissionRequestCode == permissionRequestCode){
					// 跳转到应用详情，进行权限设置
					startActivity(getAppDetailSettingIntent());
				}

			}
		});

		// 没有权限，去申请
		String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION,};
		requestPermissions(mPermissionRequestCode,permissions);

	}

	@Override
	public void onResume() {
		super.onResume();
	}

	private void initData(){

	}

	private void initView(){
		setContentView(R.layout.activity_main_drawlayout);
		bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
		bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
		mContentViewPager = (NoScrollViewPager) findViewById(R.id.content_vp);
		mContentViewPager.setOffscreenPageLimit(viewpageSize);
		mContentViewPager.setAdapter(new PagerAdapter(getSupportFragmentManager()));
		mContentViewPager.setOnPageChangeListener(new PageChangeListener());

		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerLayout.setScrimColor(Color.TRANSPARENT);// 去除阴影
		mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
		mDrawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
			@Override
			public void onDrawerStateChanged(int newState) {
			}

			@Override
			public void onDrawerSlide(View drawerView, float slideOffset) {
				View mContent = mDrawerLayout.getChildAt(0);
				View mMenu = drawerView;
				float scale = 1 - slideOffset;
				float rightScale = 0.8f + scale * 0.2f;

				if (drawerView.getTag().equals("LEFT")) {
					float leftScale = 1 - 0.3f * scale;
					ViewHelper.setScaleX(mMenu, leftScale);
					ViewHelper.setScaleY(mMenu, leftScale);
					ViewHelper.setAlpha(mMenu, 0.6f + 0.4f * (1 - scale));
					ViewHelper.setTranslationX(mContent,
							mMenu.getMeasuredWidth() * (1 - scale));
					ViewHelper.setPivotX(mContent, 0);
					ViewHelper.setPivotY(mContent,
							mContent.getMeasuredHeight() / 2);
					mContent.invalidate();
					ViewHelper.setScaleX(mContent, rightScale);
					ViewHelper.setScaleY(mContent, rightScale);
				} else {
					ViewHelper.setTranslationX(mContent,
							-mMenu.getMeasuredWidth() * slideOffset);
					ViewHelper.setPivotX(mContent, mContent.getMeasuredWidth());
					ViewHelper.setPivotY(mContent,
							mContent.getMeasuredHeight() / 2);
					mContent.invalidate();
					ViewHelper.setScaleX(mContent, rightScale);
					ViewHelper.setScaleY(mContent, rightScale);
				}
			}

			@Override
			public void onDrawerOpened(View drawerView) {
			}

			@Override
			public void onDrawerClosed(View drawerView) {
				mDrawerLayout.setDrawerLockMode(
						DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.RIGHT);
			}
		});
	}

	private void openDrawerLayout(){
		if (!mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
			mDrawerLayout.openDrawer(Gravity.LEFT);
		}
	}

	private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
		@Override
		public boolean onNavigationItemSelected(@NonNull MenuItem item) {
			switch (item.getItemId()) {
				case R.id.navigation_home:
					mContentViewPager.setCurrentItem(0);
					return true;
				case R.id.navigation_monitor:
					mContentViewPager.setCurrentItem(1);
					return true;
				case R.id.navigation_setup:
					mContentViewPager.setCurrentItem(2);
					return true;
			}
			return false;
		}
	};

	private class PageChangeListener implements ViewPager.OnPageChangeListener {
		@Override
		public void onPageSelected(int position) {
			bottomNavigationView.getMenu().getItem(position).setChecked(true);
		}

		@Override
		public void onPageScrollStateChanged(int state) {

		}

		@Override
		public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

		}
	}

	private class PagerAdapter extends FragmentPagerAdapter {
		public PagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			if (position == 0) {
				if (mHomeFragment == null) {
					mHomeFragment = new HomeFragment();
					mHomeFragment.setOnClickListener(new HomeFragment.OnClickListener() {
						@Override
						public void onItemClick(final int position) {

						}

						@Override
						public void onDrawerClick(){
							openDrawerLayout();
						}
					});
				}
				return mHomeFragment;
			}
			else if(position == 1){
				if (mMonitorFragment == null) {
					mMonitorFragment = new MonitorFragment();
				}
				return mMonitorFragment;
			}else {
				if (mAccountFragment == null) {
					mAccountFragment = new AccountFragment();
				}
				return mAccountFragment;
			}
		}

		@Override
		public int getCount() {
			return viewpageSize;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
				mDrawerLayout.closeDrawer(Gravity.LEFT);
			} else {
				if ((System.currentTimeMillis() - exitTime) > 2000) {
					Toast.makeText(getApplicationContext(), "再按返回键以退出", Toast.LENGTH_SHORT).show();
					exitTime = System.currentTimeMillis();
				} else {
					finish();
					System.exit(0);
				}
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * @desc  检查授权状态
	 * @author taoli
	 * @time 2017/2/23 0023
	 */
	private void autoMaticCheckCopyright(){
		String s = Utils.getIMEI(this);
		String ss = Utils.MD5(s).substring(0,6);
		if( !Config.getCopyrightNumber().equals(ss)){
			showCopyrightInputDialog();
		}
	}

	public void showCopyrightInputDialog( ) {
		if (mInputDialog == null) {
			mInputDialog = new InputDialog(MainActivity.this);
			Window window = mInputDialog.getWindow(); //得到对话框
			window.setWindowAnimations(R.style.dialog_anim_center_style); //设置窗口弹出动画
		}
		mInputDialog.setHint("输入授权码");
		mInputDialog.setItemClickListener(new InputDialog.OnItemClick() {
			@Override
			public void onItemClick(int position, String input) {
				if (position == 0) {
					MainActivity.this.finish();
				}else if( position == 1 ){
					String s = Utils.getIMEI(MainActivity.this);
					String ss = Utils.MD5(s).substring(0,6);
					if( !ss.equals(input)){
						showTipsDialog("授权码输入错误，软件无法激活");
					}else{
						Config.setCopyrightNumber(input);
						Toast.makeText(MainActivity.this,"软件已激活",Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
		mInputDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
			@Override
			public void onDismiss(DialogInterface dialog) {
			}
		});
		mInputDialog.setCancelable(false);
		mInputDialog.show();
	}

	public void showTipsDialog( final String tips) {
		DialogUtil.showTipsDialog(this, tips, new Runnable() {
			@Override
			public void run() {
				MainActivity.this.finish();
			}
		});
	}
}
